package cn.zero.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class WebUtil {

	public static String getPostUrlData(String url, String postData)
			throws IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new StringEntity(postData, "UTF-8"));
		HttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	public static String getUrlData(String url) throws
			IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	public static String getUrlData(String urlStr, String data)
			throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		httpURLConnection.setRequestMethod("POST");
		// 设置连接超时的时间
		httpURLConnection.setConnectTimeout(30 * 1000);
		httpURLConnection.setRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
		// 设置字符编码
		httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
		httpURLConnection.setRequestProperty("Content-Type",
				"text/xml");
		// 不使用缓存
		httpURLConnection.setUseCaches(false);
		// 允许输入输出
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);

		PrintWriter out = new PrintWriter(new OutputStreamWriter(
				httpURLConnection.getOutputStream(), "utf-8"));
		out.write(data);
		out.flush();
		out.close();
		return AppStringUtils.convertStreamToString(httpURLConnection
				.getInputStream());
	}

	public static String getNetImage(String imgUrl, String imgFileName)
			throws IOException {
		// new 一个URL对象
		URL url = new URL(imgUrl);
		// 打开链接
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		// 设置请求方式为"GET"
		httpURLConnection.setRequestMethod("GET");
		// 超时范围时间为5秒
		httpURLConnection.setConnectTimeout(5 * 1000);
		// 通过输入流获取图片数据
		InputStream ins = httpURLConnection.getInputStream();
		// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
		byte[] data = readInputStream(ins);
		// new 一个文件对象用来保存图片，默认保存当前工程根目录
		File imgFile = new File(imgFileName);
		boolean flag = imgFile.getParentFile().isDirectory();
		if (!flag) {
			imgFile.getParentFile().mkdirs();
		}

		// 创建输出流
		FileOutputStream os = new FileOutputStream(imgFile);
		// 写入数据
		os.write(data);
		// 关闭输出流
		os.close();
		return imgFile.getAbsolutePath();

	}

	public static byte[] readInputStream(InputStream ins) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		// 创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		// 每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		// 使用一个输入流从buffer里把数据读取出来
		while ((len = ins.read(buffer)) != -1) {
			// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读取的长度
			os.write(buffer, 0, len);
		}
		// 关闭输入流
		ins.close();
		// 把os里的数据写入内存
		return os.toByteArray();
	}

	public static String getPostUrlDataWithCert(String url, String postData,
			String certPath, String certPassword)
			throws IOException, KeyStoreException,
			KeyManagementException, UnrecoverableKeyException,
			NoSuchAlgorithmException {
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		File file = new File(certPath);
		InputStream instream = WebUtil.class.getResourceAsStream(certPath);// 加载本地的证书进行https加密传输
		try {
			keyStore.load(instream, certPassword.toCharArray());// 设置证书密码
		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} finally {
			instream.close();
		}

		// Trust own CA and all self-signed certs
		SSLContext sslcontext = SSLContexts.custom()
				.loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
		// Allow TLSv1 protocol only
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

		HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
				.build();

		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new StringEntity(postData, "UTF-8"));
		HttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}


}
